package com.water.tao.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.expression.ParseException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StockFetcher {

    // 假设的 API URL。请替换为真实有效的股票列表 API 地址
    // 再次强调：这是一个模拟地址，实际使用请替换为真实的股票数据API
    private static final String API_URL = "https://api.example.com/stocks/list";
    // 假设你的 API 需要一个认证 Token
    private static final String API_TOKEN = "YOUR_API_TOKEN_HERE"; // 替换为你的实际 API Token

    public static void main(String[] args) {
        try {
            List<TStock> stocks = getAStockList();
            if (!stocks.isEmpty()) {
                System.out.println("成功获取 A 股股票列表：");
                for (TStock stock : stocks) {
                    System.out.println("代码: " + stock.getCode() + ", 名称: " + stock.getName() + ", 市场: " + stock.getMarket());
                }
            } else {
                System.out.println("未能获取股票列表或列表为空。");
            }

            // 可以打印连接池状态，观察连接复用情况
            System.out.println("\nHttpClient Connection Pool Stats (after fetching stocks):");
            System.out.println(HttpClientUtil.getConnectionPoolStats());

        } catch (IOException | ParseException e) {
            System.err.println("获取股票列表时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static List<TStock> getAStockList() throws IOException, ParseException {
        // 直接使用工具类中的 doGet 方法发送请求
        // 注意：如果API需要特殊的Header，我们还需要手动构建HttpGet对象并添加Header
        // 这里为了演示，我们先假设API可以直接通过GET请求获取数据

        // 获取预配置的 HttpClient 实例
        CloseableHttpClient httpClient = HttpClientUtil.getHttpClient();
        HttpGet httpGet = new HttpGet(API_URL);

        // 添加认证头 (如果需要)
        httpGet.setHeader("Authorization", "Bearer " + API_TOKEN);
        httpGet.setHeader("Accept", "application/json");

        List<TStock> stocks = new ArrayList<>();
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            if (response.getCode() == 200) { // 检查HTTP状态码
                String responseBody = EntityUtils.toString(response.getEntity());
                // System.out.println("API 返回数据: " + responseBody); // 用于调试

                ObjectMapper mapper = new ObjectMapper();
                // 假设返回的 JSON 结构是 { "data": [ { "code": "000001", "name": "平安银行", "market": "SZ" }, ... ] }
                JsonNode rootNode = mapper.readTree(responseBody);
                JsonNode dataNode = rootNode.get("data");

                if (dataNode != null && dataNode.isArray()) {
                    for (JsonNode stockNode : dataNode) {
                        String code = stockNode.get("code").asText();
                        String name = stockNode.get("name").asText();
                        String market = stockNode.get("market").asText();
                        stocks.add(new TStock(code, name, market));
                    }
                }
            } else {
                System.err.println("API 请求失败，状态码: " + response.getCode());
                System.err.println("错误信息: " + EntityUtils.toString(response.getEntity()));
            }
        } catch (org.apache.hc.core5.http.ParseException e) {
            throw new RuntimeException(e);
        }
        return stocks;
    }
}

// 简单的股票数据模型（与之前相同）
class Stock {
    private String code;
    private String name;
    private String market;

    public Stock(String code, String name, String market) {
        this.code = code;
        this.name = name;
        this.market = market;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public String getMarket() {
        return market;
    }
}
